﻿using HDS.Common.Helper;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;

namespace HDS.Extension.ServiceExtension
{
    public static class SqlSugarSetup
    {
        public static void AddSqlsugarSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.AddScoped<ISqlSugarClient>(o =>
            {
                var listConfig = new List<ConnectionConfig>();
                var configIds = new string[] { "Sys", "Master", "Apilog" };
                foreach (var configId in configIds)
                {
                    listConfig.Add(new ConnectionConfig()
                    {
                        ConfigId = configId,
                        ConnectionString = AppSettings.GetAppSettingValue(new string[] { "ConnectionStrings", configId }),
                        DbType = DbType.MySql,
                        IsAutoCloseConnection = true,
                        // Check out more information: https://github.com/anjoy8/Blog.Core/issues/122
                        IsShardSameThread = false,
                        AopEvents = new AopEvents
                        {
                            OnLogExecuting = (sql, p) =>
                            {
#if DEBUG
                                Console.WriteLine("SQL：", GetParas(p) + "【SQL语句】：" + sql);
#endif
                            }
                        },
                        MoreSettings = new ConnMoreSettings()
                        {
                            IsAutoRemoveDataCache = true,
                            MySqlDisableNarvchar = true
                        },
                        InitKeyType = InitKeyType.Attribute
                    });
                }

                return new SqlSugarClient(listConfig);
            });
        }

        private static string GetParas(SugarParameter[] pars)
        {
            string key = "【SQL参数】：";
            foreach (var param in pars)
            {
                key += $"{param.ParameterName}:{param.Value}\n";
            }

            return key;
        }
    }
}
